import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
        hasLogin: false,
        userInfo: {},
        HTTP: "https://api.cdszly.cn/nvwa-api/",
        wxappMPID: "", //微信小程序id
        token: "",
        userInfoFetched: false,
		spaceData: {},
    },
    mutations: {
        login(state, provider) {
            state.hasLogin = true;
            state.userInfo = provider;
            state.userInfoFetched = true;
            uni.setStorage({ //缓存用户登陆状态
                key: 'userInfo',
                data: provider
            })
        },
        logout(state) {
            state.hasLogin = false;
            state.userInfo = {};
            state.userInfoFetched = false;
            uni.removeStorage({
                key: 'userInfo'
            })
        },
        // 设置token
        setToken(state, token) {
            state.token = token;
			uni.setStorageSync('token', token);
        },
        setUserInfo(state, userInfo) {
            state.userInfo = userInfo;
				uni.setStorageSync('userInfo', userInfo);
            console.log('userInfo', userInfo)
        },
		setSpaceData(state, data) {
		    state.spaceData = data;
		}
    },
    actions: {
        updateUserInfo({
            commit,
            state
        }, userInfo) {
            if (!state.userInfoFetched) { // 检查是否已经获取过用户信息
                commit('setUserInfo', userInfo);
                // commit('setUserInfoFetched', true);
            }
        },
        updateToken({
            commit
        }, token) {
            commit('setToken', token);
        },
    },
    getters: {
        getUserInfo(state) {
            return state.userInfo;
        },
        getToken(state) {
            return state.token;
        }
    }
})

export default store
